<template>
  <el-main>
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules"
      :inline="true"
      label-suffix="："
    >
      <el-form-item label="key" prop="key">
        <el-input v-model="form.key" clearable placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="title" prop="title">
        <el-input v-model="form.title" clearable placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" clearable placeholder="请选择状态">
          <el-option
            v-for="[key, value] in statusDict.data.value"
            :key="key"
            :label="value"
            :value="key"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :loading="roles.pending.value"
          @click="onSubmit"
          >搜索</el-button
        >
        <el-button type="" @click="reset(), onSubmit()">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="">
      <el-button type="primary">新建</el-button>
      <el-button type="danger">删除</el-button>
      <el-button type="success">启用</el-button>
      <el-button type="danger">禁用</el-button>
    </div>
    <el-table
      class="mt-2"
      border
      v-loading="roles.pending.value"
      row-key="key"
      :data="roles.data.value?.list || []"
      :row-class-name="
        ({ row }) => (row.status === Status.disable ? 'disable-row' : '')
      "
    >
      <el-table-column type="selection" prop="" label="" fixed>
      </el-table-column>
      <el-table-column prop="key" label="key" width="200"> </el-table-column>
      <el-table-column prop="title" label="title"> </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        align="center"
        width="60"
        v-slot="{ row }"
      >
        <el-icon
          size="20"
          :class="
            row.status === Status.enable ? 'text-success' : 'text-disabled'
          "
        >
          <icon
            :name="
              row.status === Status.enable
                ? 'mdi:checkbox-marked'
                : 'mdi:checkbox-blank-outline'
            "
          ></icon>
        </el-icon>
      </el-table-column>
      <el-table-column
        prop=""
        label="操作"
        align="center"
        v-slot="{ row }"
        width="160"
      >
        <nuxt-link
          :to="{
            name: 'system-role-key',
            params: {
              key: row.key,
            },
          }"
          custom
          v-slot="{ href, navigate }"
        >
          <el-button
            text
            type="primary"
            :href="href"
            size="default"
            @click.stop="navigate"
            >编辑</el-button
          >
        </nuxt-link>
        <el-button text type="danger" size="default">删除</el-button>

        <!-- <el-button
          text
          type="primary"
          size="default"
          @click.stop="navigateToMenuKey(row.menu.key)"
          >编辑</el-button
        > -->
      </el-table-column>
    </el-table>
    <el-pagination
      class="mt-2"
      background
      layout="->, total, sizes, prev, pager, next, jumper"
      v-model:current-page="page.page"
      v-model:page-size="page.pageSize"
      :total="roles.data.value?.total || 0"
    />
    <child-page-drawer
      exclude="system-role"
      :size="isMobile ? '100%' : '425px'"
    >
      <template #header>
        <span>角色详情</span>
      </template>
    </child-page-drawer>
  </el-main>
</template>

<script setup lang="ts">
import { Status } from '~~/types/status.d';

import { PageData } from '~~/types/pageData.d';
import { Role } from '~~/types/role.d';
import type { FormInstance, FormRules } from 'element-plus';
const isMobile = useMediaQuery('(max-width: 425px)');
const statusDict = useDict('system.status');

// 默认表单数据
const baseForm = {
  key: '',
  title: '',
  status: undefined,
};

// 默认表单数据的克隆，用于绑定输入组件
const { cloned: form, sync: reset } = useCloned(baseForm);

// 接口查询条件，与表单数据分离。
const formCloned = useCloned(form, { manual: true });
const page = ref({
  page: 1,
  pageSize: 10,
});
const query = computed(() => ({ ...formCloned.cloned.value, ...page.value }));

const rules = reactive<FormRules>({});
const formRef = ref<FormInstance>();
const roles = useAsyncData(
  () =>
    <Promise<PageData<Role>>>$fetchApi('/system/role', { query: query.value }),
  {
    default: () => ({
      list: [],
      total: 0,
    }),
  },
);

// useFetchApi('/system/role', {
//   default: () => ({
//     list: [],
//     total: 0,
//   }),
// });

watchAsyncDataError(roles);

whenever(
  () => !roles.pending.value,
  () => {
    // 修复表单，避免因修改了表单未点击搜索产生的歧义。
    form.value = useCloned(formCloned.cloned).cloned.value;
  },
);

const { trigger, ignoreUpdates } = watchTriggerable(
  query,
  useDebounceFn(roles.refresh, 300),
);

async function onSubmit() {
  if (!formRef.value) return;
  const isValid = await formRef.value.validate().catch(() => false);
  if (!isValid) return;
  ignoreUpdates(() => {
    formCloned.sync();
  });
  trigger();
}
onBeforeRouteUpdate((updateGuard) => {
  if (updateGuard.name === 'system-role') {
    trigger();
  }
});
</script>

<style scoped></style>
